import time
from datetime import datetime
from pages.excel_data_extraction import Excel_data_extraction
from config.settings import get_config
from base.base_page import BasePage

"""
封装功能函数

"""
class New_Object_Page(BasePage):
    def __init__(self, driver, device_type, logger=None):
        super().__init__(driver, device_type, logger=logger)  # 传递日志实例
        self.driver = driver
        self.config = get_config(device_type)  # 获取全局配置
        self.excel_processor = Excel_data_extraction(self.driver, device_type, logger=logger)
    ########################################  新建业务对象  ########################################

    def new_object_page(self, object_name, department, manager_name, contact_information, description):
        # 封装新建业务对象流程（已有断言）
        # 1.进入基本可用配置界面--新建业务对象
        self.enter_new_object_page()
        # 停止业务对象状态
        self.update_object_status(object_name, '停止')
        # 删除指定名称的业务对象
        self.delete_object(object_name)
        # 2.点击新建按钮
        self.newly_built_object()
        # 3.输入业务对象
        self.input_object_name(object_name)
        # 4.输入业务归属部门
        self.input_department_name(department)
        # 5.输入业务负责人
        self.input_manager_name(manager_name)
        # 6.输入业务负责人联系方式
        self.input_manager_information(contact_information)
        # 7.输入业务说明
        self.input_object_description(description)
        # 8.点击保存
        self.save_new_object(object_name)

    def enter_new_object_page(self):
        # 进入新建业务对象界面
        status = self.find_element('first_level_menu_module', 'basic_available_configure_status')
        if "ivu-menu-opened" in status.get_attribute("class"):
            if self.quick_check_element('new_object_module', 'select_object'):
                pass
            else:
                self.click('second_level_menu_module', 'new_object')
                self.soft_assert_element_visible('new_object_module', 'select_object')
        else:
            self.click('first_level_menu_module', 'basic_available_configure')
            self.soft_assert_element_visible('second_level_menu_module', 'new_object')
            self.click('second_level_menu_module', 'new_object')
            self.soft_assert_element_visible('new_object_module', 'select_object')

    def newly_built_object(self):
        # 点击新建按钮
        self.click('common_elements', 'newly_built')
        self.soft_assert_element_visible('new_object_module', 'object_new_interface_title')

    def input_object_name(self, object_name):
        # 输入业务对象
        self.input_text('new_object_module', 'business_object', object_name)
        self.soft_assert_input_value('new_object_module', 'business_object', object_name)

    def input_department_name(self, department):
        # 输入业务归属部门
        self.input_text('new_object_module', 'belonging_department', department)
        self.soft_assert_input_value('new_object_module','belonging_department', department)

    def input_manager_name(self, manager_name):
        # 输入业务负责人
        self.input_text('new_object_module', 'business_owner', manager_name)
        self.soft_assert_input_value('new_object_module', 'business_owner', manager_name)

    def input_manager_information(self, contact_information):
        # 输入业务负责人联系方式
        self.input_text('new_object_module', 'contact_information_person', contact_information)
        self.soft_assert_input_value('new_object_module',
                                               'contact_information_person', contact_information)
    def input_object_description(self, description):
        # 输入业务说明
        self.input_text('new_object_module', 'business_description', description)
        self.soft_assert_input_value('new_object_module', 'business_description', description)

    def save_new_object(self, object_name):
        # 点击保存业务对象
        self.click('new_object_module', 'new_object_save')
        self.find_element('common_elements', 'create_success')
        self.soft_assert_element_visible('new_object_module','first_object')
        self.logger.info(f'业务对象：{object_name} 保存成功')

    def select_object_page(self, object_name):
        # 根据业务对象名称筛选
        self.click('new_object_module', 'select_object')
        # 使用 find_elements 获取所有选项
        options = self.find_elements('new_object_module', 'object_filtering_all')
        # 遍历匹配项
        for option in options:
            if option.text.strip() == object_name:  # 增加容错处理（如去除空格）
                option.click()
                break
        else:
            raise ValueError(f"未找到选项：'{object_name}'")

    def update_object_status(self, object_name, object_status):
        # 修改业务对象状态
        self.enter_new_object_page()
        if self.quick_check_element('common_elements', 'no_data'):
            pass
        else:
            current_page = 1
            while True:
                name_elements = self.find_elements('new_object_module', 'object_name_all')
                # 遍历当前页
                for row_index, element in enumerate(name_elements, 1):
                    current_name = element.text.strip()
                    if current_name == object_name:
                        # 定位同行的状态
                        status = self.find_dynamic_element(
                            'new_object_module',
                            'object_status_all',
                            row_index
                        )
                        if "ivu-switch-checked" in status.get_attribute("class"):
                            if object_status == '启动':
                                pass
                            else:
                                status.click()
                                self.click('common_elements', 'confirm_button')
                                self.find_element('common_elements', 'status_update_success')
                                self.logger.info(f"接口 '{object_name}'停止成功")
                        else:
                            if object_status == '停止':
                                pass
                            else:
                                status.click()
                                self.click('common_elements', 'confirm_button')
                                self.find_element('common_elements', 'status_update_success')
                                self.logger.info(f"接口 '{object_name}'启动成功")


                # 尝试翻页
                if not self._go_to_next_page():
                    break
                current_page += 1 # 等待分页加载

    def delete_object(self, object_name):
        """
        支持分页查找并删除对象
        :param object_name: 要删除的对象名称
        """
        if self.quick_check_element('common_elements', 'no_data'):
            pass
        else:
            current_page = 1
            while True:
                # 获取当前页所有对象名称
                name_elements = self.find_elements('new_object_module', 'object_name_all')
                # 遍历当前页
                for row_index, element in enumerate(name_elements, 1):
                    if element.text.strip() == object_name:
                        self._delete_current_row(row_index)
                        self.logger.info(f"成功删除第{current_page}页的'{object_name}'")
                        return
                # 尝试翻页
                if not self._go_to_next_page():
                    break
                current_page += 1 # 等待分页加载

    def _delete_current_row(self, row_index):
        """执行单行删除操作"""
        delete_btn = self.find_dynamic_element(
            'new_object_module',
            'delete_object_all',
            row_index
        )
        # 点击删除按钮
        delete_btn.click()

        self.click('common_elements', 'confirm_button')
        self.find_element('common_elements', 'delete_success')


    def get_object_department(self, object_name, expected_department):
        # 获取指定业务对象的归属部门
        self.enter_new_object_page()
        current_page = 1
        while True:
            # 获取当前页所有接口名称元素
            name_elements = self.find_elements('new_object_module', 'object_name_all')
            # 遍历当前页
            for row_index, element in enumerate(name_elements, 1):
                current_name = element.text.strip()
                if current_name == object_name:
                    # 定位同行的归属部门元素
                    department_element = self.find_dynamic_element(
                        'new_object_module',
                        'object_department_all',
                        row_index
                    )
                    # 获取并存储地址
                    department = department_element.text.strip()
                    if department == expected_department:
                        self.logger.info(f"实际归属部门 '{department}' 预期归属部门：{expected_department}")
                    else:
                        continue
            # 尝试翻页
            if not self._go_to_next_page():
                break
            current_page += 1 # 等待分页加载

    def get_object_manager(self, object_name, expected_manager_name):
        # 获取指定业务对象的负责人
        self.enter_new_object_page()
        current_page = 1
        while True:
            # 获取当前页所有接口名称元素
            name_elements = self.find_elements('new_object_module', 'object_name_all')
            # 遍历当前页
            for row_index, element in enumerate(name_elements, 1):
                current_name = element.text.strip()
                if current_name == object_name:
                    # 定位同行的业务负责人元素
                    manager_name = self.find_dynamic_element(
                        'new_object_module',
                        'object_manager_name_all',
                        row_index
                    )
                    # 获取并存储地址
                    manager_name = manager_name.text.strip()
                    if manager_name == expected_manager_name:
                        self.logger.info(f"实际业务负责人 '{manager_name}' 预期业务负责人：{expected_manager_name}")
                    else:
                        continue
            # 尝试翻页
            if not self._go_to_next_page():
                break
            current_page += 1  # 等待分页加载

    def get_object_time(self, object_name):
        # 获取指定业务对象的创建时间
        self.enter_new_object_page()
        current_page = 1
        while True:
            # 获取当前页所有接口名称元素
            name_elements = self.find_elements('new_object_module', 'object_name_all')
            # 遍历当前页
            for row_index, element in enumerate(name_elements, 1):
                current_name = element.text.strip()
                if current_name == object_name:
                    # 定位同行的业务创建时间元素
                    create_time = self.find_dynamic_element(
                        'new_object_module',
                        'object_create_time_all',
                        row_index
                    )
                    # 获取当前时间，并格式化为只保留年月日时
                    expected_object_time = datetime.now().strftime('%Y-%m-%d %H')
                    # 获取并存储地址
                    create_time = create_time.text.strip()
                    create_time = create_time[:13]
                    if create_time == expected_object_time:
                        self.logger.info(f"实际业务负责人 '{create_time}' 预期业务负责人：{expected_object_time}")
                    else:
                        continue
            # 尝试翻页
            if not self._go_to_next_page():
                break
            current_page += 1 # 等待分页加载

    def get_object_status(self, object_name, expected_object_status):
        # 查看业务对象状态
        self.enter_new_object_page()
        current_page = 1
        while True:
            name_elements = self.find_elements('new_object_module', 'object_name_all')
            # 遍历当前页
            for row_index, element in enumerate(name_elements, 1):
                current_name = element.text.strip()
                if current_name == object_name:
                    # 定位同行的状态
                    status = self.find_dynamic_element(
                        'new_object_module',
                        'object_status_all',
                        row_index
                    )
                    if "ivu-switch-checked" in status.get_attribute("class"):
                        if expected_object_status == '启动':
                            self.logger.info(f"业务对象实际状态 '启动' 业务对象预期状态：{expected_object_status}")
                        else:
                            self.logger.error(f"业务对象实际状态 '启动' 业务对象预期状态：{expected_object_status}")
                    else:
                        if expected_object_status == '启动':
                            self.logger.error(f"业务对象实际状态 '启动' 业务对象预期状态：{expected_object_status}")
                        else:
                            self.logger.info(f"业务对象实际状态 '启动' 业务对象预期状态：{expected_object_status}")

            # 尝试翻页
            if not self._go_to_next_page():
                break
            current_page += 1 # 等待分页加载

    def export_objects(self):
        self.click('common_elements', 'export')

        excel_file = self.excel_processor.wait_for_new_excel(timeout=60)
        # 定义解析参数
        parse_params = {
            "sheet_name": "1-100",
            "start_row": 3,
            "headers": ["序号", "业务对象", "承载归属部门", "业务负责人", "业务负责人联系方式", "业务说明", "此业务对象下已建数据接口"
                        , "创建时间", "启/停状态"],
            "max_rows": 10
        }
        # 解析Excel内容
        excel_data = self.excel_processor.parse_excel(excel_file, parse_params)
        self.logger.info(excel_data)